package com.jeecms.wicool.action.car;

import static com.jeecms.common.page.SimplePage.cpn;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.jeecms.cms.manager.main.CmsLogMng;
import com.jeecms.cms.web.CmsUtils;
import com.jeecms.cms.web.WebErrors;
import com.jeecms.common.page.Pagination;
import com.jeecms.common.web.CookieUtils;
import com.jeecms.common.web.ResponseUtils;
import com.jeecms.wicool.entity.car.CarBrand;
import com.jeecms.wicool.entity.car.CarImg2;
import com.jeecms.wicool.entity.car.CarParam;
import com.jeecms.wicool.entity.car.CarSeries;
import com.jeecms.wicool.entity.car.CarType;
import com.jeecms.wicool.entity.car.UsedCar;
import com.jeecms.wicool.entity.shops.ShopInfo;
import com.jeecms.wicool.manager.car.CarBrandMng;
import com.jeecms.wicool.manager.car.CarImg2Mng;
import com.jeecms.wicool.manager.car.CarParamMng;
import com.jeecms.wicool.manager.car.CarSeriesMng;
import com.jeecms.wicool.manager.car.CarTypeMng;
import com.jeecms.wicool.manager.car.UsedCarMng;
import com.jeecms.wicool.manager.shops.WiShopInfoMng;

@Controller
public class UsedCarAct {
	private static final Logger log = LoggerFactory.getLogger(UsedCarAct.class);

	@RequestMapping("/usedCar/v_list.do")
	public String list(String title,Integer carBrandId,Integer carSeriesId,Integer carTypeId ,Integer pageNo,HttpServletRequest request, ModelMap model) {
		Pagination pagination = manager.getPage( title, carBrandId, carSeriesId, carTypeId ,cpn(pageNo),
				CookieUtils.getPageSize(request));
		List<CarBrand> listCarBrand=carBrandMng.getAll(CmsUtils.getUser(request));
		List<CarSeries> listCarSeries=carSeriesMng.getAll(CmsUtils.getUser(request));
		List<CarType> listCarType=carTypeMng.getAll(CmsUtils.getUser(request));
		CarType ct = new CarType();
		ct.setId(0);ct.setTypeName("其它");
		listCarType.add(ct);
		model.addAttribute("pagination", pagination);
		model.addAttribute("listCarBrand",listCarBrand);
		model.addAttribute("listCarSeries",listCarSeries);
		model.addAttribute("listCarType",listCarType);
		
		
		model.addAttribute("title",title);
		model.addAttribute("carBrandId",carBrandId);
		model.addAttribute("carSeriesId",carSeriesId);
		model.addAttribute("carTypeId",carTypeId);
		return "car/list_usedCar";
	}
	@RequestMapping("/usedCar/v_edit.do")
	public String edit(Integer id, HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateEdit(id, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		UsedCar usedCar = manager.findById(id);
		List<ShopInfo> listShop= shopMng.getAll(CmsUtils.getUser(request));
		
		List<CarBrand> listCarBrand=carBrandMng.getAll(CmsUtils.getUser(request));
		CarBrand cb = new CarBrand();
		cb.setId(0);cb.setBrandName("其它");
		listCarBrand.add(cb);
		List<CarSeries> listCarSeries=carSeriesMng.getAll(CmsUtils.getUser(request));
		CarSeries cs = new CarSeries();
		cs.setId(0);cs.setShortName("其它");
		listCarSeries.add(cs);
		List<CarType> listCarType=carTypeMng.getAll(CmsUtils.getUser(request));
		CarType ct = new CarType();
		ct.setId(0);ct.setTypeName("其它");
		listCarType.add(ct);
		
		model.addAttribute("usedCar",usedCar);
		model.addAttribute("listShop",listShop);
		model.addAttribute("listCarBrand",listCarBrand);
		model.addAttribute("listCarSeries",listCarSeries);
		model.addAttribute("listCarType",listCarType);
		return "car/edit_usedCar";
	}
	@RequestMapping("/usedCar/v_toView.do")
	public String toView(Integer id, HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateEdit(id, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		model.addAttribute("usedCar_id",id);
		return "car/to_view_usedCar";
	}
	@RequestMapping("/usedCar/v_view.do")
	public String view(Integer id, HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateEdit(id, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		UsedCar usedCar = manager.findById(id);
		model.addAttribute("usedCar",usedCar);
		return "car/view_usedCar";
	}
	@RequestMapping("/usedCar/v_view_usedCar_carParam.do")
	public String viewUsedCarCarParm(Integer usedCarId, HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateEdit(usedCarId, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		
		CarType carType = manager.findById(usedCarId).getCarType();
		CarParam carParam = carType.getCarParam();
		model.addAttribute("carParam",carParam);
		return "car/view_carParam";
	}
	@RequestMapping("/usedCar/o_save.do")
	public String save(UsedCar bean, Integer shopId,Integer carBrandId,Integer carSeriesId,Integer carTypeId,String[] imgUrls, String[] imgNames,
			HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateSave(bean, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		if(imgUrls!=null&&imgUrls.length>0){
			Set<CarImg2> listCarImgs=new HashSet<CarImg2>();
			for(int i=0;i<imgUrls.length;i++){
				CarImg2 carImg=new CarImg2();
				carImg.setCarCate(Short.parseShort("2"));
				carImg.setUsedCar(bean);
				carImg.setImgName(imgNames[i]);
				carImg.setImgUrl(imgUrls[i]);
				listCarImgs.add(carImg);
			}
			bean.setCarImgs(listCarImgs);
		}
		bean = manager.save(bean,shopId,carBrandId,carSeriesId,carTypeId);
		log.info("save UsedCar id={}", bean.getId());
		cmsLogMng.operating(request, "UsedCar.log.save",  "id=" + bean.getId());
		return "redirect:v_list.do";
	}
	@RequestMapping("/usedCar/o_update.do")
	public String update(UsedCar bean,Integer shopId ,Integer carBrandId,Integer carSeriesId,Integer carTypeId,String[] imgUrls, String[] imgNames,
			Integer pageNo,HttpServletRequest request,ModelMap model) {
		WebErrors errors = validateUpdate(bean.getId(), request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		SimpleDateFormat simpleTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String dateTime = simpleTime.format(new Date());
		Timestamp t = Timestamp.valueOf(dateTime);

		bean.setUpdateTime(t);
		
		//处理图片集
		//删除原有的图片集
		UsedCar c=manager.findById(bean.getId());
		if(c.getCarImgs()!=null&&c.getCarImgs().size()>0){
			Set<CarImg2>s= new HashSet<CarImg2>();
				s.addAll(c.getCarImgs());
			for(CarImg2 i:s){
				c.getCarImgs().remove(i);
				i.setUsedCar(null);
				carImg2Mng.deleteById(i.getId());
			}
		}
		if(imgUrls!=null&&imgUrls.length>0){
			Set<CarImg2> listCarImgs=new HashSet<CarImg2>();
			for(int i=0;i<imgUrls.length;i++){
				CarImg2 carImg=new CarImg2();
				carImg.setCarCate(Short.parseShort("1"));
				carImg.setUsedCar(bean);
				carImg.setImgName(imgNames[i]);
				carImg.setImgUrl(imgUrls[i]);
				listCarImgs.add(carImg);
			}
			bean.setCarImgs(listCarImgs);
		}
		//****
		if(carTypeId!=0){
			bean.setOtherCarType("");
		}
		bean=manager.update(bean,shopId,carBrandId,carSeriesId,carTypeId);
		model.addAttribute("message", "global.success");
		log.info("update UsedCar success. id={}", bean.getId());
		cmsLogMng.operating(request, "UsedCar.log.update",  "id=" + bean.getId());
		return list(null,null,null,null,pageNo,request, model);
	}

	@RequestMapping("/usedCar/v_add.do")
	public String add(ModelMap model,HttpServletRequest request) {
		UsedCar usedCar = new UsedCar();
		List<ShopInfo> listShop= shopMng.getAll(CmsUtils.getUser(request));
		
		List<CarBrand> listCarBrand=carBrandMng.getAll(CmsUtils.getUser(request));
		CarBrand cb = new CarBrand();
		cb.setId(0);cb.setBrandName("其它");
		listCarBrand.add(cb);
		List<CarSeries> listCarSeries=carSeriesMng.getAll(CmsUtils.getUser(request));
		CarSeries cs = new CarSeries();
		cs.setId(0);cs.setShortName("其它");
		listCarSeries.add(cs);
		List<CarType> listCarType=carTypeMng.getAll(CmsUtils.getUser(request));
		CarType ct = new CarType();
		ct.setId(0);ct.setTypeName("其它");
		listCarType.add(ct);
		model.addAttribute("usedCar", usedCar);
		model.addAttribute("listShop", listShop);
		model.addAttribute("listCarBrand", listCarBrand);
		model.addAttribute("listCarSeries", listCarSeries);
		model.addAttribute("listCarType", listCarType);
		return "car/add_usedCar";
	}
	
	@RequestMapping("/usedCar/o_delete.do")
	public String delete(Integer[] ids, String title,Integer carBrandId,Integer carSeriesId,Integer carTypeId ,Integer pageNo, HttpServletRequest request,
			ModelMap model) {
		WebErrors errors = validateDelete(ids, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		UsedCar[] beans = manager.deleteByIds(ids);
		for (UsedCar bean : beans) {
			log.info("delete UsedCar id={}", bean.getId());
			cmsLogMng.operating(request, "UsedCar.log.delete", "id="
					+ bean.getId() + ";name=" + bean.getTitle());
		}
		return list(title,carBrandId,carSeriesId,carTypeId,pageNo, request, model);
	}
	private WebErrors validateSave(UsedCar bean, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		return errors;
	}

	private WebErrors validateEdit(Integer id, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		if (vldExist(id, errors)) {
			return errors;
		}
		return errors;
	}

	private WebErrors validateUpdate(Integer id, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		if (vldExist(id, errors)) {
			return errors;
		}
		// TODO 验证是否为管理员，管理员不允许修改。
		return errors;
	}
	private WebErrors validateDelete(Integer[] ids, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		errors.ifEmpty(ids, "ids");
		for (Integer id : ids) {
			vldExist(id, errors);
		}
		return errors;
	}

	private boolean vldExist(Integer id, WebErrors errors) {
		if (errors.ifNull(id, "id")) {
			return true;
		}
		UsedCar entity = manager.findById(id);
		if (errors.ifNotExist(entity, UsedCar.class, id)) {
			return true;
		}
		return false;
	}
	/**
	 * 下拉选择框联动
	 * 根据品牌获取车系
	 * @param request
	 * @param response
	 * @param pid
	 * @throws Exception
	 */
	@RequestMapping("/usedCar/getCarSeries.do")
	public void getCarSeries(HttpServletRequest request,HttpServletResponse response,String bid) throws Exception{
		List<CarSeries> carSeriesList = new ArrayList<CarSeries>();
		if(StringUtils.isNotBlank(bid)){
			carSeriesList = carSeriesMng.getCarSeriesByCarBrand(Integer.parseInt(bid),CmsUtils.getUser(request));
		}
		JSONArray result = new JSONArray();
		JSONObject obj = null;
		for (CarSeries s : carSeriesList) {
			obj = new JSONObject();
			obj.put("sid", s.getId());
			obj.put("sname", s.getShortName());
			result.put(obj);
		}
		ResponseUtils.renderJson(response, result.toString());
	}
	@RequestMapping("/usedCar/getCarType.do")
	public void getCarType(HttpServletRequest request,HttpServletResponse response,String sid) throws Exception{
		List<CarType> carTypeList = new ArrayList<CarType>();
		if(StringUtils.isNotBlank(sid)){
			carTypeList = carTypeMng.getCarTypeByCarSeries(Integer.parseInt(sid),CmsUtils.getUser(request));
		}
		JSONArray result = new JSONArray();
		JSONObject obj = null;
		for (CarType t : carTypeList) {
			obj = new JSONObject();
			obj.put("tid", t.getId());
			obj.put("tname", t.getTypeName());
			result.put(obj);
		}
		ResponseUtils.renderJson(response, result.toString());
	}
	@Autowired
	private UsedCarMng manager;
	@Autowired
	private CarTypeMng carTypeMng;
	@Autowired
	private WiShopInfoMng shopMng;
	@Autowired
	private CmsLogMng cmsLogMng;
	@Autowired
	private CarBrandMng carBrandMng;
	@Autowired
	private CarSeriesMng carSeriesMng;
	@Autowired
	private CarParamMng carParamMng;
	@Autowired
	private CarImg2Mng carImg2Mng;
}
